/*
 * @Author: YMJ
 * @Date: 2020-10-30 09:58:32
 */
import router from './router'
import store from './store'
// import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
// import { initRouter } from '@/utils/setRoute'
NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // 开始进度条
  NProgress.start()

  // 设置页面标题
  document.title = getPageTitle(to.meta.title)

  // 确定用户是否已经登录
  const hasToken = store.getters.token
  if (hasToken) {
    if (to.path === '/login') {
      // 如果已登录，则重定向到主页
      next({ path: '/' })
      NProgress.done() // hack: https://github.com/PanJiaChen/vue-element-admin/pull/2939
    } else {
      // store中存在token 那不路径也会存在(刷新会被同时刷新)
      next()
      NProgress.done()
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单中，直接跳转
      next()
      NProgress.done()
    } else {
      // 缓存中存在token，直接添加到store中
      if (getToken()) {
        store.commit('user/SET_TOKEN', getToken())
        store.dispatch('user/menu').then(list => {
          router.addRoutes([...list, { path: '*', redirect: '/', hidden: true }])
          next({ ...to, replace: true })
          NProgress.done()
        })
      } else {
        next(`/login?redirect=${to.path}`)
        NProgress.done()
      }
    }
  }
})

router.afterEach(() => {
  // 完成进度条
  NProgress.done()
})
